package com.atguigu.network;

import org.junit.Test;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * @author yihu
 * @create 2021-06-15 11:49
 * @email:1057202547@qq.com
 * @dec:
 * 客户端发送文件给服务端，服务端将文件保存在本地。
 */
public class TCPTest2 {
      @Test
      public void client() {
          Socket socket = null;
          OutputStream os = null;
          FileInputStream fis = null;
          try {
              InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
              socket = new Socket(inetAddress,8898);
              os = socket.getOutputStream();
              fis = new FileInputStream("randomAccessFile2.png");

              byte[] buffte = new byte[1024];
              int len;
              while ((len = fis.read(buffte))!=-1){
                  os.write(buffte,0,len);
              }
          } catch (IOException e) {
              e.printStackTrace();
          } finally {
              if(socket!=null){
                  try {
                      socket.close();
                  } catch (IOException e) {
                      e.printStackTrace();
                  }
              }
              if(os!=null){
                  try {
                      os.close();
                  } catch (IOException e) {
                      e.printStackTrace();
                  }
              }
              if(fis!=null){
                  try {
                      fis.close();;
                  } catch (IOException e) {
                      e.printStackTrace();
                  }
              }
          }
      }
    //应该用try catch finally 次处偷懒
    @Test
    public void server() throws  IOException{
        ServerSocket ss = new ServerSocket(8898);
        Socket socket = ss.accept();
        InputStream is = socket.getInputStream();
        FileOutputStream fis = new FileOutputStream(new File("clinet1.png"));

        byte[] buffte = new byte[1024];
        int len;
        while ((len = is.read(buffte))!=-1){
            fis.write(buffte,0,len);
        }

        ss.close();
        socket.close();
        is.close();
        fis.close();
    }

}
